<template>
	<div>
		<div class="container">
			<div class="header">
				<router-link to="">
				<i class="iconfont icon-back" @click="$router.back()"></i>
			</router-link>
				<li>
					<p class="cartword">购物车</p>
				</li>
				<li>
					<span class="editbtn" v-show="isLogin && list.length > 0"
						@click="editMode = !editMode">{{ editMode?"完成": "编辑" }}
					</span>
				</li>
			</div>
			<!--没登录的时候-->
			<div v-if="!isLogin">
				<img :src="noResultPng" alt="">
				<p>亲，你还没登录</p>
				<router-link to="/login">
					<button @click="$router.push('/login?target=' + $route.fullPath)">
						立即登录
					</button>
				</router-link>
			</div>
			<!--登录了-->
			<template v-else>
				<!--登陆了，如果没有购物记录-->
				<div class="cartnull" v-if="list.length === 0 && checkStatus.length === 0">
					<img :src="noResultPng" alt="" class="cartimg">
					<p class="wordcart">亲，你的购物车为空，快去选购商品</p>
					<router-link to="/home" class="indexword">去首页</router-link>
				</div>
				<!--登陆了且有购物记录-->
				<template v-else>
					<ul class="list content">
						<li v-for="(item, i) in list" :key="item.id" class="list-content">
							<div class="left" v-if="checkStatus.length > 0">
								<!--普通状态下显示的i-->
								<i class="checkbox" :class="{ checked: checkStatus[i].checked }"
									@click="checkStatus[i].checked = !checkStatus[i].checked" v-if="!editMode"></i>
								<i class="checkbox" :class="{ checked: checkStatus[i].editChecked }"
									@click="checkStatus[i].editChecked = !checkStatus[i].editChecked" v-else></i>

								<div class="avatar-wrapper" @click="detail()">
									<img :src="item.avatar" alt="">
								</div>
							</div>

							<div class="item-info">
								<router-link to="/detail">
									<h5  v-text="item.name"></h5>
									<p v-text="item.brief"></p>
								</router-link>
								<span class="price-wrapper">￥<span class="price" v-text="item.price"></span>.00</span>
								<div class="btn">
									<MiCount :count="item.count" @decrease="decreaseHandler(item.id)"
										@increase="increaseHandler(item.id)">
									</MiCount>
								</div>
							</div>
						</li>
					</ul>
					<div class="footer">
						<!--普通状态下的页脚-->
						<div class="footer-box" v-if="!editMode">
							<div class="footer-left" @click="allChecked = !allChecked">
								<i class="checkbox" :class="{ checked: allChecked }"></i>
								<p>全选</p>
							</div>
							<div class="footer-right">
								<p>合计:<span class="moneny">￥{{ total }}</span></p>
								<button :disabled="sum === 0" @click="batchtotal()">
									<span>结算</span>
									<span v-if="sum > 0">({{ sum }})</span>
								</button>
							</div>
						</div>
						<!--编辑状态下的页脚-->
						<div class="footer-box" v-else>
							<div class="footer-left">
								<i class="checkbox" :class="{ checked: allEditChecked }"
									@click="allEditChecked = !allEditChecked"></i>
								<p>全选</p>
							</div>
							<div class="footer-right">
								<button :disabled="removeIds.length === 0" @click="batchRemoveHandler">
									<span>删除</span>
								</button>
							</div>
						</div>
					</div>

				</template>
			</template>
		</div>
	</div>
</template>

<script>
import noResultPng from './no_result_cart3.png'
import MiCount from '../../components/MiCount/MiCount.vue';
import { mapState, } from 'vuex'
import { CartApi } from '../../api'

export default {
	name: "Cart",
	components: { MiCount },
	data() {
		return {
			isLogin: sessionStorage.getItem("token") ? true : false,
			noResultPng,
			editMode: false,
			checkStatus: [],
			list2: []
		}
	},
	async created() {
		if (!this.isLogin) return;
		try {
			const list = await this.$store.dispatch('cart/init');
			this.checkStatus = list.reduce((result, item) => {
				result.push({ id: item.id, checked: true, editChecked: false });
				return result;
			}, []);
		} catch (e) {/**/
		}
	},
	computed: {
		...mapState('cart', ["list"]),
		allChecked: {
			get: function () {
				return this.checkStatus.every(item => item.checked);
			},
			set: function (value) {
				this.checkStatus.forEach(item => item.checked = value);
			}
		},
		allEditChecked: {
			get: function () {
				return this.checkStatus.every(item => item.editChecked);
			},
			set: function (value) {
				this.checkStatus.forEach(item => item.editChecked = value);
			}

		},
		total: function () {
			return this.list.reduce((result, item) => {
				if (this.checkStatus.findIndex(item2 => item2.id === item.id && item2.checked) !== -1) {
					result += item.count * item.price;
				}
				return result;
			}, 0);
		},
		sum: function () {
			return this.list.reduce((result, item) => {
				if (this.checkStatus.findIndex(item2 => item2.id === item.id && item2.checked) !== -1) {
					result += item.count;
				}
				return result;
			}, 0);
		},
		removeIds: function () {
			return this.checkStatus.reduce((ids, item) => {
				if (item.editChecked) ids.push(item.id);
				return ids;
			}, []);
		}
	},

	methods: {
		detail() {
			this.$router.replace(this.$route.query.target)
		},
		async decreaseHandler(id) {
			try {
				await this.$store.dispatch("cart/decrease", id);
				this.$miNotice('数量减少成功..');
			} catch (e) {/**/
			}
		},
		async increaseHandler(id) {
			try {
				await this.$store.dispatch('cart/increase', id);
				this.$miNotice('数量增加成功..');
			} catch (e) {/**/ }
		},
		async batchRemoveHandler() {
			try {
				await this.$miConfirm('真删?');
				await this.$store.dispatch("cart/batchRemove", this.removeIds);
			} catch (e) {/**/ }
		},
		async batchtotal() {
			try {
				this.list2 = await CartApi.getList();
				const listD = [];
				this.checkStatus.forEach(items => {
					if (items.checked) {
						this.list2.forEach(item => {
							if (items.id === item.id) {
								listD.push(item.id)
							}
						})
					}
				});
				this.$router.push({
					path: '/myorder',
				})
				sessionStorage.setItem("id", JSON.stringify(listD))
			} catch (e) {/**/ }
		}
	},

}
</script>

<style scoped>
* {
	margin: 0;
	padding: 0;
}

li {
	list-style: none;
}

.container {
	display: flex;
	width: 100vw;
	height: 100vh;
	flex-direction: column;
}

.header {
	display: flex;
	flex-shrink: 0;
	justify-content: space-evenly;
	align-items: center;
	background-color: #f4f4f4;
	height: 21vw;
}

.indexword {
	margin-top: 30px;
	padding: 10px;
	border: 1px solid #835f3f;
	border-radius: 30px;
}

.wordcart {
	margin-top: 17px;
}

.header li:nth-child(2) {
	display: flex;
	flex-grow: 1;
	align-items: center;
	justify-content: center;
	color: rgba(0, 0, 0, 0.8);
	font-size: 18px;
}

.header li:first-child,
.header li:last-child {
	flex-shrink: 0;
}

.header li:last-child {
	padding-right: 14px;
	color: rgba(0, 0, 0, 0.8);
	font-size: 14px;
}

i.checkbox {
	flex-shrink: 0;
	width: 24px;
	height: 24px;
	background-image: url(./icon_checkbox_uncheck.png);
	background-size: 100% 100%;
}

i.checkbox.checked {
	background-image: url(./icon_checkbox_check.png);
}

.content {
	flex-grow: 1;
	background-color: #f4f4f4;
}

.list-content {
	display: flex;
	align-items: center;
	margin-left: 10px;
	margin-right: 10px;
	background-color: #fff;
	margin-bottom: 5px;
	border-radius: 10px;
}

.left {
	display: flex;
	margin-left: 5px;
	align-items: center;
}

.checkbox {
	width: 24px;
	height: 24px;
	background-size: 24px;
	flex-shrink: 0;
	margin-right: 10px;
	background-image: url("./icon_checkbox_uncheck.png");
}

.checkbox.checked {
	background-image: url("./icon_checkbox_check.png");
}

.btn {
	display: flex;
}

.btn button {
	border: none;
	background-color: transparent;
	padding: 0 8px;
}

.btn span {
	border-left: 1px solid #ccc;
	border-right: 1px solid #ccc;
	padding: 0 8px;
}

.footer {
	height: 40px;
	border-top: 1px solid #ccc;
	border-bottom: 1px solid #ccc;
}

.footer-box {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.footer-left {
	display: flex;
	flex-shrink: 0;
	margin-left: 10px;
}

.footer-left p {
	color: rgba(0, 0, 0, 0.8);
	font-size: 14px;
	font-weight: 500;
	margin-left: 5px;
}

.footer-right {
	display: flex;
	align-items: center;
	flex-shrink: 0;
}

.footer-right p {
	color: rgba(0, 0, 0, 0.8);
	font-size: 14px;
	font-weight: 500;
}

.footer button {
	background: linear-gradient(to right, rgb(251, 36, 0), rgb(255, 106, 0)) rgb(191, 17, 17);
	border-radius: 19px;
	height: 38px;
	width: 100px;
	border: none;
	color: #fff;
	float: right;
}

.footer-right button {
	float: right;
	margin-right: 10px;
}

ul.list {
	padding: 0 10px;
	overflow: auto;
}

ul.list li {
	display: flex;
	align-items: center;
}

ul.list .avatar-wrapper {
	width: 150px;
	margin: 0 10px;
}

ul.list .avatar-wrapper img {
	width: 100%;
}

.iconfont {
	font-size: 25px;
	margin-left: 18px;
}

.cartword {
	font-size: 20px;
	color: rgba(0, 0, 0, 0.8);
}

.editbtn {
	font-size: 16px;
}

.moneny {
	font-size: 16px;
	margin-right: 10px;
	color: red;
}

.cartimg {
	width: 200px;
	height: 200px;
	margin: 0 auto;
	margin-top: 50px;
}

.cartnull {
	display: flex;
	flex-direction: column;
	align-items: center;
}
</style>